<template>
  <form-wrap :schema="formSchema" :rules="rules" @register="formRegister" />
</template>
<script setup lang="ts">
  import { useForm } from '@/hooks/form';
  import { useValidator } from '@/hooks/validator';
  import { useDictStore } from '@/store';
  import { filterTree } from '@/utils/tree';

  const props = defineProps({
    data: {
      type: Object,
      required: true,
    },
    treeList: {
      type: Array,
      required: true,
    },
    currentParentId: {
      type: String,
      default: () => null,
    },
  });

  const dictStore = useDictStore();
  const { required } = useValidator();
  const { formRegister, formMethods } = useForm();
  const { setValues, submitForm } = formMethods;

  const formSchema = computed<FormSchema[]>(() => {
    return [
      { field: 'id', hidden: true },
      {
        field: 'parentId',
        label: '上级',
        type: 'a-tree-select',
        props: {
          fieldNames: {
            key: 'id',
            title: 'name',
          },
          data: tree.value,
        },
      },
      {
        field: 'name',
        label: '名称',
        type: 'Input',
        props: {
          maxlength: 30,
        },
      },
      {
        field: 'sequence',
        label: '排序',
        type: 'InputNumber',
        props: {
          precision: 0,
          max: 99999,
          min: 0,
        },
      },
      {
        field: 'state',
        label: '状态',
        type: 'Select',
        componentProps: {
          options: dictStore.getItems('State'),
        },
      },
    ];
  });

  const rules = reactive({
    name: [required()],
    state: [required()],
  });

  const tree = ref<any[]>([]);

  onMounted(() => {
    if (props.data) {
      setValues(props.data);
    }
    let allTreeList: Array<any> = [
      { id: '0', name: '根组织', depth: 0, children: props.treeList },
    ];
    tree.value = filterTree(allTreeList, props.data?.id, 2);
  });

  const submit = async () => {
    return await submitForm();
  };

  defineExpose({
    submit,
  });
</script>
